package com.hmdp.task;

import cn.hutool.json.JSONUtil;
import com.hmdp.constant.RedisConstants;
import com.hmdp.dto.RedisData;
import com.hmdp.entity.Shop;
import com.hmdp.service.IShopService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * date: 2023/9/10 20:04
 * author: MR.孙
 */
@Component
public class ShopDataToRedisTask {

    @Autowired
    IShopService shopService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private static final Logger log = LoggerFactory.getLogger(ShopDataToRedisTask.class);

    //开启线程，进行缓存预热【缓存重建】
    @Async("newAsyncExecutor")
    public void saveShopToRedis(Long id, Long expireSeconds) throws InterruptedException {

        log.info("开始缓存预热异步任务，商铺id->{},过期时间->{}", id, expireSeconds);
        long start = System.currentTimeMillis();

        //查询商铺数据
        Shop shop = shopService.getById(id);
        //设置逻辑过期时间
        LocalDateTime expire = LocalDateTime.now().plusSeconds(expireSeconds);
        RedisData redisData = RedisData.builder()
                .data(shop)
                .expireTime(expire)
                .build();

        //模拟 重建的耗时
        Thread.sleep(200);
        //写入到Redis 逻辑过期不需要设置过期时间
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
        long end = System.currentTimeMillis();
        log.info("缓存预热异步任务结束, 耗时:{}", end-start);
    }


}
